package com.kgc.servlet;

import com.alibaba.fastjson.JSONObject;
import com.kgc.entity.Provider;
import com.kgc.entity.Role;
import com.kgc.entity.User;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.kgc.service.SmbmsService;
import com.kgc.service.impl.SmbmsServiceImpl;
import com.kgc.util.UUIDUtil;
import org.springframework.ui.Model;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SmbmsServlet extends HttpServlet {

    private SmbmsService sc;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("utf-8");
//
//        String mode = request.getParameter("mode");
//        if ("login".equals(mode)){
//            this.login(request,response);
//        }else if ("usermanage".equals(mode)){
//            this.showUser(request,response);
//        }else if ("selectrole".equals(mode)){
//            this.selectRolename(request,response);
//        }else if ("insertuser".equals(mode)){
//            this.insertUser(request,response);
//        }else if ("selectuser".equals(mode)){
//            this.selectUser(request,response);
//        }else if ("deleteuser".equals(mode)){
//            this.deleteUser(request,response);
//        }else if ("providermanage".equals(mode)){
//            this.listProvider(request,response);
//        }
    }

    public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{

        String username = request.getParameter("username");

        String password = request.getParameter("password");

        User user = sc.getUserByusernameAndpassword(username);

        String resultView = "login.jsp";
        if (user == null){
            request.setAttribute("loginFlag","用户名不存在！");

        }else{
            if (!password.equals(user.getUserpassword())){
                request.setAttribute("passwordFlag","密码错误！");


            }else{
                resultView = "frame.jsp";
                //用户登录信息存放session
                HttpSession session = request.getSession();
                session.setAttribute("loginUser",user);
            }
        }
        request.getRequestDispatcher(resultView).forward(request,response);
    }

    public void showUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String username = request.getParameter("name");
        String userRole = request.getParameter("userRole");
        int currentPage = Integer.parseInt(request.getParameter("currentPage"));

        //获取列表数据
        List<User> list = sc.listUser(username,userRole,currentPage);
        //总记录数
        int totalCount = sc.countUsers(username,userRole);
        //总页数
        int totalPage = totalCount % 4 == 0 ? totalCount / 4 : totalCount / 4 + 1;

        List<Role> list1 = sc.listRolename();

        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("list1",list1);
        map.put("totalCount",totalCount);
        map.put("totalPage",totalPage);

        String json = JSONObject.toJSONString(map);

        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }

    public void insertUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        try {
            //创建FileItemFactory对象
            FileItemFactory factory = new DiskFileItemFactory();
            //创建ServletFileupload
            ServletFileUpload upload = new ServletFileUpload(factory);
            //解析request
            List<FileItem> list = upload.parseRequest(request);
            //创建User对象
            User u = new User();
            for(FileItem fi : list){
                //判定普通表单还是文件表单
                if(fi.isFormField()){
                    //普通文本
                    //获取表单的name 和对应的value
                    String name = fi.getFieldName();
                    String value = fi.getString("utf-8");
                    if("userCode".equals(name)){
                        u.setUsercode(value);
                    }else if("userName".equals(name)){
                        u.setUsername(value);
                    }else if("userPassword".equals(name)){
                        u.setUserpassword(value);
                    }else if("gender".equals(name)){
                        u.setGender(Integer.parseInt(value));
                    }else if("birthday".equals(name)){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date d = sdf.parse(value);
                        u.setBirthday(d);
                    }else if("phone".equals(name)){
                        u.setPhone(value);
                    }else if("address".equals(name)){
                        u.setAddress(value);
                    }else if("userRole".equals(name)){
                        Role r = new Role();
                        r.setId(Integer.parseInt(value));
                        u.setRole(r);
                    }

                }else{
                    //文件
                    //获取应用的绝对地址
                    ServletContext application = this.getServletContext();
                    //获取发布项目的跟路径
                    String rootPath = application.getRealPath("/");
                    System.out.println(rootPath);
                    //创建文件夹
                    String dirName = "uploadImg";
                    String dirPath = rootPath + dirName;
                    File dirFile = new File(dirPath);
                    if(!dirFile.exists()){
                        dirFile.mkdir();
                    }

                    //获取文件名
                    String photoName = fi.getName();
                    //获取全球唯一号
                    String uuid = UUIDUtil.createUUID();
                    String newName = uuid + photoName.substring(photoName.lastIndexOf("."));
                    //获取文件流
                    InputStream is = fi.getInputStream();
                    byte[] b = new byte[(int) fi.getSize()];
                    is.read(b,0,b.length);

                    //写文件
                    String photoPath = dirPath + "/" + newName;
                    FileOutputStream fos = new FileOutputStream(photoPath);
                    fos.write(b);
                    fos.flush();
                    fos.close();

                    //获取表单的name
                    String name = fi.getFieldName();
                    if("cardphoto".equals(name)){
                        u.setCardphoto(dirName + "/" +newName);
                    }else {
                        u.setWorkphoto(dirName + "/" +newName);
                    }

                }
            }
            //调用保存
            HttpSession session = request.getSession();
            User loginUser = (User) session.getAttribute("loginUser");
            //创建人
            u.setCreateby(loginUser.getId());
            //创建时间
            u.setCreationdate(new Date());
            int flag = sc.insertUser(u);
            request.setAttribute("insertFlag",flag);
            request.getRequestDispatcher("userlist.jsp").forward(request,response);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    public void selectUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        int id = Integer.parseInt(request.getParameter("id"));
        User user = sc.selectUser(id);
        request.setAttribute("user",user);
        request.getRequestDispatcher("userview.jsp").forward(request,response);
    }

    public void selectRolename(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        List<Role> list = sc.listRolename();
        request.setAttribute("rolename",list);
        request.getRequestDispatcher("useradd.jsp").forward(request,response);
    }

    public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        int id = Integer.parseInt(request.getParameter("id"));
        int flag = sc.deleteUser(id);
        request.setAttribute("flag",flag);
        request.getRequestDispatcher("userlist.jsp").forward(request,response);
    }

    public void listProvider(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//        List<Provider> list = sc.listProvider();
//
//        String json = JSONObject.toJSONString(list);
//        PrintWriter out = response.getWriter();
//
//        out.print(json);
//        out.flush();
//        out.close();
    }
}
